import {getDeptList} from "@/api/system/dept";
import {Dept} from "@/views/system/dept/hooks/useTable";
import {getCurrentInstance, ref, watch} from "vue";
import useTable from "@/views/system/user/hooks/useTable";
import {searchForm}from "@/views/system/user/hooks/useSearch"
import useBuildTreeSelectOptions from "@/hooks/useBuildTreeSelectOptions/useBuildTreeSeclectOptions";
export const currentDept = ref<Dept>()
const treeLoading = ref(false)
export default function useDeptTree() {
    const instance = getCurrentInstance()
    const {getUserDataList} = useTable()
    const {treeSelectOptions,buildTreeSelectOptions}=useBuildTreeSelectOptions()
    const deptTree = ref<Dept[]>()
    const filterText = ref('')
    function getDeptTree() {
        treeLoading.value = true
        getDeptList({dataStatus:1}).then(res=>{
            treeLoading.value = false
            deptTree.value  = res.data
            buildTreeSelectOptions(res.data,"id",'name')
            treeSelectOptions.value = res.data
        })
    }
    function filterDeptTree(val: string,data: Dept){
        if(!val){
            return true
        }
        return  data.name.includes(val)
    }
    function currentNodeChange(val: Dept){
        currentDept.value = val
    }
    getDeptTree()
    watch(filterText,(val)=>{
        //eslint-disable-next-line
        (instance?.refs.deptTreeRef as any).filter(val)
    })
    watch(currentDept,()=>{
        searchForm.deptId = currentDept.value?.id
        getUserDataList()
    })
    return {
        deptTree,
        filterText,
        filterDeptTree,
        currentNodeChange,
        treeLoading,
        treeSelectOptions
    }
}
